<?php
/**
 * Created by PhpStorm.
 * User: Shroom Ari
 * Date: 11/21/14
 * Time: 9:43 PM
 */
class Promotion extends MY_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->layout->setLayout('backend/index');
        $session_data = $this->session->userdata('logged_in');
        $usergroup_id = $session_data['usergroup_id'];
        if ($usergroup_id!=1) redirect('../petshop');
    }
    public function listPromotion($page=1){
        $data['seo']['title']='Promotion';
        $total_promotion= $this->mpromotion->countAll();
        $perpage = 5;
        $config['base_url'] = "/petshop/backend/promotion/listPromotion/"; // xác định trang phân trang
        $config['total_rows'] = $total_promotion; // xác định tổng số record
        $config['per_page'] = $perpage; // xác định số record ở mỗi trang
        $config['num_links'] = 10;
        $config['cur_page'] =$page;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['_config']= $config;
        $data['_page']=$page;
        $offset = ($page-1) * $perpage;
        $data['promotion']= $this->mpromotion->getPromotion($perpage,$offset);
        if (isset($_POST['submit']) and $_POST['submit'] == 'delete'){
            $this->mpromtoion->delete();
        }
        $this->layout->view('backend/layout/promotion', $data);
    }
    public function newPromotionAjax(){
        $start_date = $this->input->get('start_date');
        $end_date = $this->input->get('end_date');
        $type = $this->input->get('type');
        if ($type ==0){
            $data['products'] = $this->mpromotion->getProductHaveNoPromotion($start_date, $end_date);
        }
        elseif ($type == 1){
            $id = $this->input->get('id');
            $data['products'] = $this->mpromotion->getPromotionNotEdit($start_date, $end_date, $id);
        }
        $this->load->view('backend/layout/new_promotion_ajax', $data);
    }

    public function newPromotion(){
        $data['seo']['title']='Add Promotion';
        $data['error'] = false;
        $data['products'] = $this->mproduct->getProduct();
        $data['promotions'] = $this->mpromotion->getAllPromotion();
        if (isset($_POST['submit']) and $_POST['submit'] == 'add'){
            $this->form_validation->set_rules('name', 'Name', 'required|min_length[3]|xss_clean');
            $this->form_validation->set_rules('content', 'Content', 'required|xss_clean');
            $this->form_validation->set_rules('start_date', 'Start Date', 'required|xss_clean');
            $this->form_validation->set_rules('end_date', 'End Date', 'required|xss_clean|callback_check_enddate');
            $this->form_validation->set_rules('discount', 'Discount', 'required|xss_clean|numeric|callback_check_discount');
            if($this->form_validation->run())
            {
                $product_ids = $this->input->post('product');
                $data_promotion = array(
                    'promotion_name' => $this->input->post('name'),
                    'url_image' => $this->save_image(),
                    'start_date' => $this->input->post('start_date'),
                    'end_date' => $this->input->post('end_date'),
                    'content' => $this->input->post('content'),
                    'discount' =>$this->input->post('discount')
                );
                $id = $this->mpromotion->createPromotion($data_promotion);
                if($id)
                {
                    foreach($product_ids as $product_id){
                        $data_detail = array(
                            'promotion_id' => $id,
                            'product_id' => $product_id,
                        );
                        $this->mpromotiondetail->create($data_detail);
                    }
                    redirect('backend/promotion/listPromotion');
                }
                else {
                    $data['error'] = true;
                }
            }
        }
        $this->layout->view('backend/layout/new_promotion', $data);

    }

    function check_discount($discount){
        if (floatval($discount) >1 and floatval($discount) <0){
            $this->form_validation->set_message('check_discount', 'Discount is not valid');
            return false;
        }
        else{
            return TRUE;
        }
    }

    function check_enddate($end_date){
        $start_date = $this->input->post('start_date');
        if (strtotime($start_date)> strtotime($end_date)){
            $this->form_validation->set_message('check_enddate', 'Start Date must lower than End Date');
            return false;
        }
        else{
            return true;
        }
    }
    function save_image(){
        $name = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10).".jpg";

        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/jpg")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/x-png")
                || ($_FILES["file"]["type"] == "image/png"))
            && in_array($extension, $allowedExts)) {
            $file_name = $_SERVER["DOCUMENT_ROOT"]."/petshop/public/images/".$name;
            if(file_exists($file_name)) {
                chmod($file_name,0755); //Change the file permissions if allowed
                unlink($file_name); //remove the file
            }
            if ($_FILES["file"]["error"] > 0) {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
                echo 1;
            }
        }
        return $name;
    }

    public function delete(){
        $this->mpromotion->delete($this->input->post('id'));
    }
    public function edit($id){
        $data['seo']['title']='Edit Promotion';
        $data['promotionById']= $this->mpromotion->getPromotionById($id);
        if (isset($_POST['submit']) and $_POST['submit'] == 'edit'){
            $this->form_validation->set_rules('name', 'Name', 'required|min_length[3]|xss_clean');
            $this->form_validation->set_rules('content', 'Content', 'required|xss_clean');
            $this->form_validation->set_rules('start_date', 'Start Date', 'required|xss_clean');
            $this->form_validation->set_rules('end_date', 'End Date', 'required|xss_clean|callback_check_enddate');
            $this->form_validation->set_rules('discount', 'Discount', 'required|xss_clean|callback_check_discount');
            if($this->form_validation->run())
            {
                if ($_FILES["file"]["error"] == 0){

                    $dt = array(
                        'promotion_name' => $this->input->post('name'),
                        'url_image' => $this->save_image(),
                        'start_date' => $this->input->post('start_date'),
                        'end_date' => $this->input->post('end_date'),
                        'content' => $this->input->post('content')
                    );
                }
                else{

                    $dt = array(
                        'promotion_name' => $this->input->post('name'),
                        'start_date' => $this->input->post('start_date'),
                        'end_date' => $this->input->post('end_date'),
                        'content' => $this->input->post('content')
                    );
                }
                if($this->mpromotion->updatePromotion($dt, $id))
                {
                    redirect('backend/promotion/listPromotion');
                }
            }
        }
        $this->layout->view('backend/layout/edit_promotion', $data);
    }
}

